import config from './config.js'

export const uploadImage = (params) => {
	return new Promise((presolve, preject) => {
		if ({}.toString.call(params.tempFilePaths) != '[object Array]') {
			throw new TypeError(`上传图片参数 tempFilePaths 类型错误!`)
		}
		//路径数组为空时  不上传
		if (params.tempFilePaths.length == 0) {
			presolve([])
			return
		}
		// wx.showLoading({
		// 	title: '上传图片中...',
		// 	mask: true
		// });

		let uploads = []
		params.tempFilePaths.forEach((item, i) => {
			uploads[i] = new Promise((resolve) => {
				wx.uploadFile({
					url: config.host + params.url,
					filePath: item.url,
					name: 'fileList',
					header: params.header || {
						'Content-Type': 'application/json',
						'authorization': wx.getStorageSync('authorization')
					},
					success(res) {
						if (typeof(res.header.authorization) !== "undefined") {
							wx.setStorageSync('authorization', res.header.authorization)
						}
						
						if (res.data.code === 50035 || res.data.code === 50037) {
							if (typeof(wx.getStorageSync('authorization')) === "undefined") {
								wx.showToast({
									title: res.data.message,
									icon: 'none',
									duration: 2000
								})
							}
							wx.removeStorageSync('authorization')
							wx.reLaunch({
								url: '/pages/login/login'
							})
						} else {
							resolve(JSON.parse(res.data))
						}	
					},
					fail(err) {
						console.log(err)
						// wx.hideLoading()
					}
				})
			})
		})

		Promise.all(uploads).then(res => {
			//图片上传完成
			presolve(res)
			// wx.hideLoading()
		}).catch(err => {
			preject(err)
			// wx.hideLoading()
			wx.showToast({
				title: '上传失败请重试',
				icon: 'none'
			})
		})
	})
}
